package com.ld.collegetask;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.google.gson.Gson;
import com.ld.collegetask.beans.BaseJsonBean;
import com.ld.collegetask.beans.DynamicBean;
import com.ld.collegetask.beans.DynamicCommentBean;
import com.ld.collegetask.beans.DynamicCommentListBean;
import com.ld.collegetask.databinding.ActivityDynamicMemberInfoBinding;
import com.ld.collegetask.serverInterface.RequestSerives;
import com.ld.collegetask.utils.AppApplication;
import com.ld.collegetask.utils.SharePreference;

import java.util.ArrayList;
import java.util.List;

import me.leefeng.promptlibrary.PromptDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class DynamicMemberInfoActivity extends BaseActivity {

    private ActivityDynamicMemberInfoBinding binding;

    private Integer userId = 0;
    private Integer dynamicId = 0;
    private Integer pageNo = 0;
    private Integer totalPage = 0;
    private DynamicBean dynamicBean;
    private PromptDialog promptDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dynamic_member_info);
        //dynamicId = Integer.parseInt(getIntent().getStringExtra("dynamicId"));
        dynamicId = getIntent().getIntExtra("dynamicId", 0);
        SharePreference sp = new SharePreference(getBaseContext());
        userId = sp.getUserId();
        setTitleView(this,binding.ilTitle,true,true,false,false);
        setTitle("评论");
        setLoadingView(this,binding.ilLoading);
        promptDialog = new PromptDialog(this);

        loading_go();

        showView();
    }

    private void showView() {
        binding.text1.setOnClickListener(this);
        binding.rlDynamicPinlun.setOnClickListener(this);
    }

    @Override
    public void loading() {
        dynamic_member_info();
        ContentList.clear();
        pageNo = 0;
        totalPage = 0;
        dynamic_member_comment_list();
    }


    private void dynamic_member_info() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.dynamic_member_info(dynamicId,userId);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    dynamicBean = gson.fromJson(base.getJson(), DynamicBean.class);
                    binding.setDynamicBean(dynamicBean);
                    loading_end();
                } else {
                    loading_error();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading_error();
            }
        });
    }

    private void dynamiccomment_member_save(String comment) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.dynamiccomment_member_save(userId,dynamicId,dynamicBean.getDynamicUserId(),comment);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    promptDialog.dismiss();
                    loading_go();
                } else {
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }

    private void dynamic_member_comment_list() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.dynamic_member_comment_list(dynamicId,pageNo);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    DynamicCommentListBean commentList = gson.fromJson(base.getJson(), DynamicCommentListBean.class);
                    pageNo = commentList.getPageNo();
                    totalPage = commentList.getTotalPage();
                    ContentList.addAll(commentList.getCommentList());
                    setListAdapter(ContentList);
                    binding.edittext1.setText("");
                    loading_end();
                } else {
                    loading_error();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading_error();
            }
        });
    }

    private List<DynamicCommentBean> ContentList = new ArrayList<>();
    private MyListAdapter<DynamicCommentBean> adapter;

    private void setListAdapter(List<DynamicCommentBean> list) {
        if (pageNo <= 1) {
            adapter = new MyListAdapter(this, list, R.layout.item_member_dynamic_comment_list, com.ld.collegetask.BR.dynamicCommentBean);
            binding.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    public class MyListAdapter<T> extends BaseAdapter {
        private Context context;//上下文环境
        private List<T> list;//通用的，不知道数据
        private int layoutId;//通用的，不知道布局
        private int variableId;//变量的id

        // 通过构造器关联数据源与数据适配器
        public MyListAdapter(Context context, List<T> list, int layoutId, int variableId) {
            this.context = context;
            this.list = list;
            this.layoutId = layoutId;
            this.variableId = variableId;
        }

        @Override
        public int getCount() {
            if (list != null)
                return list.size();
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == list.size() - 1) {
                if (pageNo < totalPage) {
                    pageNo++;
                   dynamic_member_info();
                }
            }

            ViewDataBinding viewDataBinding = null;
            if (convertView == null) {
                viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(context), layoutId, parent, false);
            } else {
                viewDataBinding = DataBindingUtil.getBinding(convertView);
            }
            viewDataBinding.setVariable(variableId, list.get(position));
            return viewDataBinding.getRoot();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.text_1:
                if (binding.edittext1.getText().toString().trim().equals("")){
                    promptDialog.showWarn("请填写说说内容");
                    break;
                }
                hideSoftKeyboard();
                promptDialog.showLoading("正在提交");
                dynamiccomment_member_save(binding.edittext1.getText().toString());
                break;
            case R.id.rl_dynamic_pinlun:
                binding.rlDynamicPinlun.setFocusable(true);
                break;
        }
    }
}
